import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import { segment } from "oicq"
import fs from "fs"
import path from "path"
import data from '../model/XiuxianData.js'
import Config from "../model/Config.js";
import { get_player_img, get_equipment_img, get_najie_img } from './showData.js'
import common from "../model/common.js"


//插件根目录
const __dirname = path.resolve() + path.sep + "plugins" + path.sep + "xiuxian-emulator-plugin";
// 文件存放路径
const __PATH = {
    //用户数据
    player_path: path.join(__dirname, "/resources/data/xiuxian_player"),
    //装备
    equipment_path: path.join(__dirname, "/resources/data/xiuxian_equipment"),
    //纳戒
    najie_path: path.join(__dirname, "/resources/data/xiuxian_najie"),
    //源数据
    lib_path: path.join(__dirname, "/resources/data/item"),
    //公告数据
    log_path: path.join(__dirname, "/logs"),
}

let xiuxianSetFile = "./plugins/xiuxian-emulator-plugin/config/xiuxian/xiuxian.yaml";
if (!fs.existsSync(xiuxianSetFile)) {
    fs.copyFileSync("./plugins/xiuxian-emulator-plugin/defSet/xiuxian/xiuxian.yaml", xiuxianSetFile);
}


//设置缓存参数,用来判断用户正在做什么
let tupo_CD = [];
let Lilian_CD = [];
let Yihongyuan_key = false;

//处理消息
export class xiuxian extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: 'Yunzai_Bot_修仙v3.0',
            /** 功能描述 */
            dsc: '修仙模块',
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 600,
            rule: [
                {
                    //开发用的,记得删
                    reg: '^#修仙测试$',
                    fnc: 'xiuxian_test'
                },
                {
                    reg: '^#踏入仙途$',
                    fnc: 'Create_player'
                },
                {
                    reg: '^#(修仙重生|再入仙途|重新修仙)$',
                    fnc: 'reCreate_player'
                },
                {
                    reg: '^#我的存档$',
                    fnc: 'Show_player'
                },
                {
                    reg: '^#我的纳戒$',
                    fnc: 'Show_najie'
                },
                {
                    reg: '^#(升级纳戒|纳戒升级)$',
                    fnc: 'Lv_up_najie'
                },
                {
                    reg: '^#(改名.*)|(设置宣言.*)$',
                    fnc: 'Change_player_name'
                },
                {
                    reg: '^#修仙签到$',
                    fnc: 'daily_gift'
                },
                {
                    reg: '^#突破$',
                    fnc: 'Level_up'
                },
                {
                    reg: '^#(存|取)灵石(.*)$',
                    fnc: 'Take_lingshi'
                },
                {
                    reg: '^#(猜大小|金银坊)$',
                    fnc: 'Duchang'
                },
                {
                    reg: '^#万宝阁$',
                    fnc: 'Wanbaoge_list'
                },
                {
                    reg: '^#怡红院$',
                    fnc: 'Yihongyuan'
                },
                {
                    reg: '^#怡红院色图(开|关)$',
                    fnc: 'Yihongyuan_key'
                },
                {
                    reg: '^#(装备|使用|服用|学习)((.*)|(.*)*(.*))$',
                    fnc: 'Player_use'
                },
                {
                    reg: '^#购买((.*)|(.*)*(.*))$',
                    fnc: 'Buy_comodities'
                },
                {
                    reg: '^#出售((.*)|(.*)*(.*))$',
                    fnc: 'Sell_comodities'
                },
                {
                    reg: '(^#*打工$)|(^#*打工(.*)(分|分钟)$)',
                    fnc: 'Dagong'
                },
                {
                    reg: '(^#闭关$)|(^#闭关(.*)(分|分钟)$)',
                    fnc: 'Biguan'
                },
                {
                    reg: '^(梭哈)|(押注.*)|(大|小)$',
                    fnc: 'duboCheck'
                },
                {
                    reg: '^打劫$',
                    fnc: 'Dajie'
                },
                {
                    reg: '^(切磋|以武会友)$',
                    fnc: 'biwu'
                },
                {
                    reg: '^(孝敬前辈|资助后辈|赠送灵石).*$',
                    fnc: 'Give_lingshi'
                },
                {
                    reg: '^#(修为|强者)榜$',
                    fnc: 'TOP_xiuwei'
                },
                {
                    reg: '^#(财富|肥羊|富豪|灵石)榜$',
                    fnc: 'TOP_lingshi'
                },
                {
                    reg: '^#(出门|外出)(探险|历练|冒险)$',
                    fnc: 'Lilian'
                },
                {
                    reg: '^#发(福利|补偿).*$',
                    fnc: 'Fuli'
                },
                {
                    reg: '^#金银坊记录$',
                    fnc: 'jinYinFangLog'
                },
                {
                    reg: '^#(最近公告|福利记录)$',
                    fnc: 'last_Log'
                },
                {
                    reg: '^#来张卡片$',
                    fnc: 'getOneCard'
                }
            ]
        })
        this.xiuxianConfigData = Config.getConfig("xiuxian", "xiuxian");
    }


    async xiuxian_test(e) {
        if (!e.isMaster) {
            e.reply("仅限主人操作");
            return;
        }
        console.log('配置信息', this.xiuxianConfigData)
        return;
    }



    //#踏入仙途
    async Create_player(e) {
        let usr_qq = e.user_id;
        //判断是否为匿名创建存档
        if (usr_qq == 80000000) {
            e.reply("不支持匿名创建存档");
            return;
        }
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (ifexistplay) {
            e.reply("已经有存档了");
            this.Show_player(e);
            return;
        }
        //初始化玩家信息
        let File_msg = fs.readdirSync(__PATH.player_path);
        let n = File_msg.length + 1;
        let talent = await get_random_talent();
        let new_player = {
            "名号": `路人甲${n}号`,
            "灵根": talent,
            "境界": "江湖草莽",
            "修为": 0,
            "灵石": 200,
            "学习的功法": [],
            "宣言": "这个人很懒还没有写",
            "修炼效率提升": talent.eff,
            "连续签到天数": 0,
            "基础血量": data.Level_list.find(item => item.level == "江湖草莽").基础血量,
            "基础防御": data.Level_list.find(item => item.level == "江湖草莽").基础防御,
            "基础攻击": data.Level_list.find(item => item.level == "江湖草莽").基础攻击,
            "基础暴击": data.Level_list.find(item => item.level == "江湖草莽").基础暴击,
            "当前血量": 1

        }
        await Write_player(usr_qq, new_player);

        //初始化装备
        let new_equipment = {
            "武器": data.equipment_list.find(item => item.name == "烂铁匕首"),
            "护具": data.equipment_list.find(item => item.name == "破铜护具"),
            "法宝": data.equipment_list.find(item => item.name == "廉价炮仗")
        }
        await Write_equipment(usr_qq, new_equipment);

        //初始化纳戒
        let new_najie = {
            "等级": 1,
            "灵石上限": 5000,
            "灵石": 0,
            "装备": [],
            "丹药": [],
            "道具": [],
            "功法": []
        }
        await Write_najie(usr_qq, new_najie);
        await Add_HP(usr_qq, 999999);
        this.Show_player(e);
        return;
    }


    //重新修仙
    async reCreate_player(e) {
        let usr_qq = e.user_id;
        //有无存档
        //fs.existsSync(`${__PATH.player_path}/${usr_qq}.json`);
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            e.reply("没存档你重生个锤子!");
            return;
        }
        let now = new Date();
        let nowTime = now.getTime(); //获取当前时间戳
        let lastrestart_time = await redis.get("xiuxian:player:" + usr_qq + ":last_reCreate_time");//获得上次重生时间戳,
        lastrestart_time = parseInt(lastrestart_time);
        console.log("lastrestart_time", lastrestart_time);
        let rebornTime = parseInt(60000 * this.xiuxianConfigData.CD.reborn)
        console.log("lastrestart_time", lastrestart_time);
        if (nowTime < lastrestart_time + rebornTime) {
            let waittime_m = Math.trunc((lastrestart_time + rebornTime - nowTime) / 60 / 1000);
            let waittime_s = Math.trunc(((lastrestart_time + rebornTime - nowTime) % 60000) / 1000);
            e.reply(`每${rebornTime / 60 / 1000}分钟只能重生一次` + `剩余cd:${waittime_m}分 ${waittime_s}秒`);
            return;
        }
        /** 设置上下文 */
        this.setContext('RE_xiuxian');
        /** 回复 */
        await e.reply('一旦重生一切从头开始,你真的要重生吗?回复:【重生】或者【算了】进行选择', false, { at: true });
        return;
    }


    //重生方法
    async RE_xiuxian(e) {
        let usr_qq = e.user_id;
        /** 内容 */
        let new_msg = this.e.message;
        let choice = new_msg[0].text;
        let now = new Date();
        let nowTime = now.getTime(); //获取当前时间戳
        if (choice == "算了") {

            await this.reply('放弃重生,继续修行');
            /** 结束上下文 */
            this.finish('RE_xiuxian');
            return;
        }
        else if (choice == "重生") {
            //重生牵扯到宗门模块
            let player = await data.getData("player", usr_qq);
            if (isNotNull(player.宗门)) {
                console.log("有宗门");
                if (player.宗门.职位 != "宗主") {//不是宗主
                    let ass = data.getAssociation(player.宗门.宗门名称);
                    ass[player.宗门.职位] = ass[player.宗门.职位].filter(item => item != usr_qq);
                    ass["所有成员"] = ass["所有成员"].filter(item => item != usr_qq);//原来的成员表删掉这个B
                    await data.setAssociation(ass.宗门名称, ass);
                    delete player.宗门;
                    await data.setData("player", usr_qq, player);
                    console.log("退出宗门成功");
                }
                else {//是宗主
                    let ass = data.getAssociation(player.宗门.宗门名称);
                    if (ass.所有成员.length < 2) {
                        console.log("只有宗主一个人,直接删除宗门");
                        fs.rmSync(`${data.filePathMap.association}/${player.宗门.宗门名称}.json`);
                    }
                    else {
                        ass["所有成员"] = ass["所有成员"].filter(item => item != usr_qq);//原来的成员表删掉这个B
                        //随机一个幸运儿的QQ,优先挑选等级高的
                        let randmember_qq;
                        if (ass.长老.length > 0) { randmember_qq = await get_random_fromARR(ass.长老); }
                        else if (ass.内门弟子.length > 0) { randmember_qq = await get_random_fromARR(ass.内门弟子); }
                        else { randmember_qq = await get_random_fromARR(ass.所有成员); }

                        let randmember = await data.getData("player", randmember_qq);//获取幸运儿的存档
                        ass[randmember.宗门.职位] = ass[randmember.宗门.职位].filter((item) => item != randmember_qq);//原来的职位表删掉这个幸运儿
                        ass["宗主"] = randmember_qq;//新的职位表加入这个幸运儿
                        randmember.宗门.职位 = "宗主";//成员存档里改职位
                        await data.setData("player", randmember_qq, randmember);//记录到存档
                        await data.setAssociation(ass.宗门名称, ass);//记录到宗门
                    }
                    console.log("退出宗门成功");
                }

            }
            fs.rmSync(`${__PATH.player_path}/${usr_qq}.json`);
            fs.rmSync(`${__PATH.equipment_path}/${usr_qq}.json`);
            fs.rmSync(`${__PATH.najie_path}/${usr_qq}.json`);
            e.reply([segment.at(usr_qq), "当前存档已清空!开始重生"]);
            await this.Create_player(e);
            redis.set("xiuxian:player:" + usr_qq + ":last_reCreate_time", nowTime);//redis设置本次改名时间戳

        }
        else {
            this.setContext('RE_xiuxian');
            await this.reply('请回复:【重生】或者【算了】进行选择', false, { at: true });
            return;
        }
        /** 结束上下文 */
        this.finish('RE_xiuxian');
        return;
    }

    //#我的存档
    async Show_player(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let img = await get_player_img(e);
        e.reply(img);
        return;
    }


    //#我的纳戒
    async Show_najie(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let img = await get_najie_img(e);
        e.reply(img);
        return;
    }


    //Lv_up_najie纳戒升级
    async Lv_up_najie(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) { return; }
        let najie = await Read_najie(usr_qq);
        let player = await Read_player(usr_qq);
        let najie_num = this.xiuxianConfigData.najie_num
        let najie_price = this.xiuxianConfigData.najie_price
        if (najie.等级 == najie_num.length) {
            e.reply("你的纳戒已经是最高级的了")
            return;
        }
        if (player.灵石 < najie_price[najie.等级]) {
            e.reply(`灵石不足,还需要准备${najie_price[najie.等级] - player.灵石}灵石`)
            return;
        }
        await Add_灵石(usr_qq, -najie_price[najie.等级]);
        najie.灵石上限 = najie_num[najie.等级];
        najie.等级 += 1;
        //console.log(najie);
        await Write_najie(usr_qq, najie);
        e.reply(`你的纳戒升级成功,花费了${najie_price[najie.等级 - 1]}灵石,目前纳戒灵石存储上限为${najie.灵石上限},可以使用【#我的纳戒】来查看`)
        return;
    }


    //改名
    async Change_player_name(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        //检索方法
        var reg = new RegExp(/改名|设置宣言/);
        let func = reg.exec(e.msg);
        if (func == "改名") {
            let new_name = e.msg.replace("#改名", '');
            new_name = new_name.replace(" ", '');
            new_name = new_name.replace("+", '');
            if (new_name.length == 0) {
                e.reply("改名格式为:【#改名张三】请输入正确名字");
                return;
            }
            else if (new_name.length > 8) {
                e.reply("玩家名字最多八字");
                return;
            }
            let player = {};
            let now = new Date();
            let nowTime = now.getTime(); //获取当前日期的时间戳
            //let Yesterday = await shijianc(nowTime - 24 * 60 * 60 * 1000);//获得昨天日期
            let Today = await shijianc(nowTime);
            let lastsetname_time = await redis.get("xiuxian:player:" + usr_qq + ":last_setname_time");//获得上次改名日期,
            lastsetname_time = parseInt(lastsetname_time);
            lastsetname_time = await shijianc(lastsetname_time);


            console.log(Today.Y)
            console.log(lastsetname_time.Y)
            console.log(Today.M)
            console.log(lastsetname_time.M)
            console.log(Today.D)
            console.log(lastsetname_time.D)
            if (Today.Y == lastsetname_time.Y && Today.M == lastsetname_time.M && Today.D == lastsetname_time.D) {
                e.reply("每日只能改名一次");
                return;
            }
            player = await Read_player(usr_qq);
            if (player.灵石 < 100) {
                e.reply("改名需要100灵石");
                return;
            }
            player.名号 = new_name;
            redis.set("xiuxian:player:" + usr_qq + ":last_setname_time", nowTime);//redis设置本次改名时间戳
            player.灵石 -= 100;
            await Write_player(usr_qq, player);
            //Add_灵石(usr_qq, -100);
            this.Show_player(e);
            return;
        }
        else if (func == "设置宣言") {
            let new_msg = e.msg.replace("#设置宣言", '');
            new_msg = new_msg.replace(" ", '');
            new_msg = new_msg.replace("+", '');
            if (new_msg.length == 0) {
                e.reply("设置宣言格式为:【#设置宣言我要成仙】");
                return;
            }
            else if (new_msg.length > 50) {
                e.reply("宣言最多50字符");
                return;
            }
            let player = {};
            let now = new Date();
            let nowTime = now.getTime(); //获取当前日期的时间戳
            //let Yesterday = await shijianc(nowTime - 24 * 60 * 60 * 1000);//获得昨天日期
            let Today = await shijianc(nowTime);
            let lastsetxuanyan_time = await redis.get("xiuxian:player:" + usr_qq + ":last_setxuanyan_time");//获得上次改宣言日期,
            lastsetxuanyan_time = parseInt(lastsetxuanyan_time);
            lastsetxuanyan_time = await shijianc(lastsetxuanyan_time);

            if (Today.Y == lastsetxuanyan_time.Y && Today.M == lastsetxuanyan_time.M && Today.D == lastsetxuanyan_time.D) {
                e.reply("每日只能设置一次宣言");
                return;
            }
            player = await Read_player(usr_qq);
            player.宣言 = new_msg;
            redis.set("xiuxian:player:" + usr_qq + ":last_setxuanyan_time", nowTime);//redis设置本次设置宣言时间戳
            await Write_player(usr_qq, player);
            this.Show_player(e);
            return;
        }
    }


    //签到
    async daily_gift(e) {
        let usr_qq = e.user_id;
        //有无账号
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let now = new Date();
        let nowTime = now.getTime(); //获取当前日期的时间戳
        let Yesterday = await shijianc(nowTime - 24 * 60 * 60 * 1000);//获得昨天日期
        let Today = await shijianc(nowTime);
        let lastsign_time = await getLastsign(usr_qq);//获得上次签到日期
        if (Today.Y == lastsign_time.Y && Today.M == lastsign_time.M && Today.D == lastsign_time.D) {
            e.reply(`今日已经签到过了`);
            return;
        }
        let Sign_Yesterday;        //昨日日是否签到
        if (Yesterday.Y == lastsign_time.Y && Yesterday.M == lastsign_time.M && Yesterday.D == lastsign_time.D) {
            Sign_Yesterday = true;
        }
        else {
            Sign_Yesterday = false;
        }
        await redis.set("xiuxian:player:" + usr_qq + ":lastsign_time", nowTime);//redis设置签到时间
        let player = await data.getData("player", usr_qq);
        if (player.连续签到天数 == 7 || !Sign_Yesterday) {//签到连续7天或者昨天没有签到,连续签到天数清零
            player.连续签到天数 = 0;
        }
        player.连续签到天数 += 1;
        await data.setData("player", usr_qq, player);
        //给奖励
        let gift_lingshi = player.连续签到天数 * 500;
        let gift_xiuwei = player.连续签到天数 * 300;
        await Add_灵石(usr_qq, gift_lingshi);
        await Add_修为(usr_qq, gift_xiuwei);
        let msg = [
            segment.at(usr_qq),
            `已经连续签到${player.连续签到天数}天了,获得了${gift_lingshi}灵石,获得了${gift_xiuwei}修为`
        ]
        e.reply(msg);
        return;
    }


    //突破
    async Level_up(e) {
        let usr_qq = e.user_id;
        //有无账号
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        if (tupo_CD[usr_qq]) {
            e.reply("突破CD中哦");
            return true;
        }
        let player = await Read_player(usr_qq);
        let now_level = player.境界;
        let now_exp = player.修为;
        let need_exp = data.Level_list.find(item => item.level == now_level).exp;
        let now_level_id = data.Level_list.find(item => item.level == now_level).level_id;
        if (now_level_id == 38) {
            e.reply(`你已经是无上大能,此界之天花板`);
            return;
        }
        if (now_exp < need_exp) {
            e.reply(`修为不足,再积累${need_exp - now_exp}修为后方可突破`);
            return;
        }

        if (now_level == "渡劫期") {
            e.reply("您是渡劫期修士，现在开始渡劫,祝你好运")
            await sleep(5000);
            let jie = ["一九雷劫", "三九雷劫", "六九雷劫", "九九雷劫", "尘世劫", "心魔劫", "天雷劫"];
            let losermsg = [
                `渡劫失败,您最终倒在了一九雷劫的神威之下`,
                `渡劫失败,您最终倒在了三九雷劫的神威之下`,
                `渡劫失败,您最终倒在了六九雷劫的神威之下`,
                `渡劫失败,您最终倒在了九九雷劫的神威之下`,
                `渡劫失败,您最终没有抵挡住尘世的羁绊`,
                `渡劫失败,您被心魔所吞噬`,
                `历经七道雷劫，突破重重困难,最终还是由于体力不支倒在了天雷劫的神威之下`
            ];
            for (let i in jie) {
                let dec_blood = Math.trunc(Math.random() * (214285 - 142857) + 142857);
                dec_blood=0;
                player.当前血量 -= dec_blood;
                e.reply(`${jie[i]}落下,你受到了${dec_blood}点雷劫伤害,你的血量还剩余${player.当前血量}`);
                await sleep(2000);
                if (player.当前血量 <= 0) {
                    player.当前血量 = 0;
                    player.修为 -= parseInt(need_exp / 4);
                    await Write_player(usr_qq, player);
                    e.reply(losermsg[i]);
                    return;
                }
            }
        }

        let rand = Math.random();
        let prob = 1 - (now_level_id - 1) / 50;
        if (rand > prob && now_level != "渡劫期") {//运气不好失败了
            //一个CD
            tupo_CD[usr_qq] = true;
            tupo_CD[usr_qq] = setTimeout(() => {
                if (tupo_CD[usr_qq]) {
                    delete tupo_CD[usr_qq];
                }
            }, 60000 * this.xiuxianConfigData.CD.player_level_up);//这里是冷却时间，单位毫秒，60000=60秒.

            let bad_time = Math.random();//增加多种突破失败情况，顺滑突破丢失修为曲线
            if (bad_time > 0.9) {
                await Add_修为(usr_qq, -1 * need_exp * 0.4);
                e.reply(`突然听到一声鸡叫,鸡..鸡..鸡...鸡你太美！！！是翠翎恐蕈，此地不适合突破，快跑！险些走火入魔，丧失了` + (need_exp) * 0.4 + "修为");
                return;
            }
            else if (bad_time > 0.8) {
                await Add_修为(usr_qq, -1 * need_exp * 0.2);
                e.reply(`突破瓶颈时想到树脂满了,险些走火入魔，丧失了` + (need_exp) * 0.2 + "修为");
                return;
            }
            else if (bad_time > 0.7) {
                await Add_修为(usr_qq, -1 * need_exp * 0.1);
                e.reply(`突破瓶颈时想起背后是药园，刚种下掣电树种子，不能被破坏了，打断突破，嘴角流血，丧失了` + (need_exp) * 0.1 + "修为");
                return;
            }
            else if (bad_time > 0.1) {
                e.reply(`憋红了脸，境界突破失败,等到${this.xiuxianConfigData.CD.player_level_up}分钟后再尝试吧`);
                return;
            }
            else {
                await Add_修为(usr_qq, -1 * need_exp * 0.2);
                e.reply(`突破瓶颈时想起怡红院里的放肆,想起了金银坊里的狂热,险些走火入魔，丧失了` + (need_exp) * 0.2 + "修为");
                return;
            }

        }

        //境界提升,修为扣除,攻防血重新加载,当前血量拉满
        player.境界 = data.Level_list.find(item => item.level_id == now_level_id + 1).level;
        player.修为 -= need_exp;
        player.基础血量 = data.Level_list.find(item => item.level == player.境界).基础血量;
        player.基础防御 = data.Level_list.find(item => item.level == player.境界).基础防御;
        player.基础攻击 = data.Level_list.find(item => item.level == player.境界).基础攻击;
        player.基础暴击 = data.Level_list.find(item => item.level == player.境界).基础暴击;
        await Write_player(usr_qq, player);
        let equipment = await Read_equipment(usr_qq);
        await Write_equipment(usr_qq, equipment);
        await Add_HP(usr_qq, 999999999);
        e.reply(`突破成功,当前境界为${player.境界}`);
        this.Show_player(e);
        return;
    }


    //万宝阁
    async Wanbaoge_list(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let msg = [
            "***欢迎来到万宝阁***\n本店应有尽有,童叟无欺\n【#购买+物品名称*数量】\n【#出售+物品名称*数量】",
            "其中：\"\*\"需输入,\"\+\"不输入",
            "****商品列表****",
        ];
        for (var i in data.commodities_list) {
            if (data.commodities_list[i].class == "装备") {
                msg.push(`【${data.commodities_list[i].name}】 售价:${data.commodities_list[i].出售价 * 1.5}  类别:${data.commodities_list[i].class} ${data.commodities_list[i].type}  属性加成:攻${data.commodities_list[i].atk}防${data.commodities_list[i].def}血${data.commodities_list[i].HP}暴${data.commodities_list[i].bao}`);
            }
            if (data.commodities_list[i].class == "丹药") {
                if (data.commodities_list[i].type == "血量") {
                    msg.push(`【${data.commodities_list[i].name}】 售价:${data.commodities_list[i].出售价 * 1.5}  类别:${data.commodities_list[i].class}  作用:血量增加 ${data.commodities_list[i].HPp * 100}% * 血量上限 + ${data.commodities_list[i].HP} `);
                }
                if (data.commodities_list[i].type == "修为") {
                    msg.push(`【${data.commodities_list[i].name}】 售价:${data.commodities_list[i].出售价 * 1.5}  类别:${data.commodities_list[i].class}  作用:修为增加 ${data.commodities_list[i].exp} `);
                }
            }
            if (data.commodities_list[i].class == "道具") {
                //msg.push("\n");
                msg.push(`【${data.commodities_list[i].name}】 售价:${data.commodities_list[i].出售价 * 1.5}  类别:${data.commodities_list[i].class} ${data.commodities_list[i].type}  作用: ${data.commodities_list[i].desc} `);
            }
            if (data.commodities_list[i].class == "功法") {
                //msg.push("\n");
                msg.push(`【${data.commodities_list[i].name}】 售价:${data.commodities_list[i].出售价 * 1.5}  类别:${data.commodities_list[i].class}   作用: 闭关修炼效率增加${data.commodities_list[i].修炼加成 * 100}% `);
            }
        }
        await ForwardMsg(e, msg);
        return;
    }


    async Yihongyuan(e) {
        let usr_qq = e.user_id;
        if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        if (action != null) {
            //人物有动作查询动作结束时间
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }
        let player = await Read_player(usr_qq);
        if (player.灵石 < 100) {
            e.reply(`门口的大汉粗鲁的将你赶出来:"哪来的野小子,没钱还敢来学人家公子爷寻欢作乐?" 被人看出你囊中羞涩,攒到100灵石再来吧`);
            return;
        }
        var rand = Math.random();
        //rand = 0.75;
        if (rand < 0.7) {
            let randexp = 90 + parseInt(Math.random() * 20);
            e.reply(`花了100个灵石,你好好放肆了一番,奇怪的修为增加了` + randexp);
            await Add_修为(usr_qq, randexp);
            await Add_灵石(usr_qq, -100);
            if (Yihongyuan_key) {
                setu(e);
            }
            return;
        }
        else if (rand > 0.8) {
            await Add_灵石(usr_qq, -100);
            e.reply([segment.at(usr_qq), "花了50个灵石,本想好好放肆一番,却赶上了扫黄,无奈在衙门被教育了一晚上,最终大彻大悟,决定回去闭关修炼"]);
            let action_time = 2 * 60 * 1000;//持续时间，单位毫秒
            let arr = {
                "action": "闭关",//动作
                "end_time": new Date().getTime() + action_time,//结束时间
                "is_jiesuan": "0",//是否结算
                "time": action_time//持续时间
            };
            if (e.isGroup) {
                arr.group_id = e.group_id;
            }
            await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));//redis设置动作


            // biguaning(e, usr_qq, 2);
            return;
        } else {
            //console.log(player.灵石);
            let lingshi = player.灵石;
            lingshi = Math.trunc(lingshi * 3 / 4);
            //console.log(lingshi);
            e.reply([segment.at(usr_qq), "这一次，你进了一个奇怪的小巷子，那里衣衫褴褛的漂亮姐姐说要找你玩点有刺激的，你想都没想就进屋了。\n",
                "没想到进屋后不多时遍昏睡过去。醒来发现自己被脱光扔在郊外,浑身上下只剩一条裤衩子了。仰天长啸：也不过是从头再来！"]);
            await Add_灵石(usr_qq, -lingshi);
            return;
        }
    }


    //怡红院色图开关
    async Yihongyuan_key(e) {
        if (!e.isMaster) {
            e.reply("只有主人可以执行操作");
            return;
        }
        //检索方法
        var reg = new RegExp(/开|关/);
        let func = reg.exec(e.msg);
        //console.log(func);
        switch (func[0]) {
            case '开':
                Yihongyuan_key = true;
                e.reply(`怡红院色图已开启`);
                return;
            case '关':
                Yihongyuan_key = false;
                e.reply(`怡红院色图已关闭`);
                return;

        }
        return;
    }

    //存取灵石
    async Take_lingshi(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        //检索方法
        var reg = new RegExp(/取|存/);
        let func = reg.exec(e.msg);
        let msg = e.msg.replace(reg, '');
        msg = msg.replace("#", '');
        let lingshi = msg.replace("灵石", '');
        if (func == "存" && lingshi == "全部") {
            let P = await Read_player(usr_qq);
            lingshi = P.灵石;
        }
        if (func == "取" && lingshi == "全部") {
            let N = await Read_najie(usr_qq);
            lingshi = N.灵石
        }

        if (parseInt(lingshi) != parseInt(lingshi)) {
            e.reply([segment.at(usr_qq), `请在指令后面加上灵石数量`]);
            return;
        } else {
            lingshi = parseInt(lingshi);
            if (lingshi < 1) {
                e.reply([segment.at(usr_qq), `灵石数量不能为负数`]);
                return;
            }
        }
        if (func == "存") {
            let player_lingshi = await Read_player(usr_qq);
            player_lingshi = player_lingshi.灵石;
            if (player_lingshi < lingshi) {
                e.reply([segment.at(usr_qq), `灵石不足,你目前只有${player_lingshi}灵石`]);
                return;
            }
            let najie = await Read_najie(usr_qq);
            if (najie.灵石上限 < najie.灵石 + lingshi) {
                await Add_najie_灵石(usr_qq, najie.灵石上限 - najie.灵石);
                await Add_灵石(usr_qq, -najie.灵石上限 + najie.灵石);
                e.reply([segment.at(usr_qq), `已为您放入${najie.灵石上限 - najie.灵石}灵石,纳戒存满了`]);
                return;
            }
            await Add_najie_灵石(usr_qq, lingshi);
            await Add_灵石(usr_qq, -lingshi);
            e.reply([segment.at(usr_qq), `储存完毕,你目前还有${player_lingshi - lingshi}灵石,纳戒内有${najie.灵石 + lingshi}灵石`]);
            return;
        }
        if (func == "取") {
            let najie = await Read_najie(usr_qq);
            if (najie.灵石 < lingshi) {
                e.reply([segment.at(usr_qq), `纳戒灵石不足,你目前最多取出${najie.灵石}灵石`]);
                return;
            }
            let player_lingshi = await Read_player(usr_qq);
            player_lingshi = player_lingshi.灵石;
            await Add_najie_灵石(usr_qq, -lingshi);
            await Add_灵石(usr_qq, lingshi);
            e.reply([segment.at(usr_qq), `本次取出灵石${lingshi},你的纳戒还剩余${najie.灵石 - lingshi}灵石`]);
            return;
        }
        return;
    }


    //#(装备|服用|使用)物品*数量
    async Player_use(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        //检索方法
        var reg = new RegExp(/装备|服用|使用|学习/);
        let func = reg.exec(e.msg);
        let msg = e.msg.replace(reg, '');
        msg = msg.replace("#", '');
        let code = msg.split("\*");
        let thing_name = code[0];
        let quantity = 0;
        if (parseInt(code[1]) != parseInt(code[1])) { quantity = 1; }
        else if (parseInt(code[1]) < 1) { e.reply(`输入物品数量小于1,现在默认为1`); quantity = 1; }
        else { quantity = parseInt(code[1]); }
        //看看物品名称有没有设定,是不是瞎说的
        if (!data.daoju_list.find(item => item.name == thing_name) && !data.danyao_list.find(item => item.name == thing_name) && !data.equipment_list.find(item => item.name == thing_name) && !data.gongfa_list.find(item => item.name == thing_name)) {
            e.reply(`你在瞎说啥呢?哪来的【${thing_name}】?`);
            return;
        }
        if (func == "装备") {
            console.log("装备装备");
            //x是纳戒内有的数量
            let x = await exist_najie_thing(usr_qq, thing_name, "装备");
            if (!x) {//没有
                e.reply(`你没有【${thing_name}】这样的装备`);
                return;
            }
            if (x < quantity) {//不够
                e.reply(`你目前只有【${thing_name}】*${x},数量不够`);
                return;
            }
            //Add_najie_thing(usr_qq, thing_name, "装备", -1);
            await instead_equipment(usr_qq, thing_name);
            let img = await get_equipment_img(e);
            e.reply(img);
            //this.Show_player(e);
            //this.Show_najie(e);
            return;
        }

        if (func == "服用") {
            console.log("服用丹药");
            let x = await exist_najie_thing(usr_qq, thing_name, "丹药");
            if (!x) {//没有
                e.reply(`你没有【${thing_name}】这样的丹药`);
                return;
            }
            if (x < quantity) {//不够
                e.reply(`你目前只有【${thing_name}】*${x},数量不够`);
                return;
            }
            Add_najie_thing(usr_qq, thing_name, "丹药", -quantity);
            let this_danyao = data.danyao_list.find(item => item.name == thing_name);
            if (this_danyao.type == "血量") {
                let player = await Read_player(usr_qq);
                let blood = parseInt(player.血量上限 * this_danyao.HPp + this_danyao.HP);
                await Add_HP(usr_qq, quantity * blood);
                let now_HP = await Read_player(usr_qq);
                e.reply(`服用成功,当前血量为:${now_HP.当前血量} `);
                return;
            }
            if (this_danyao.type == "修为") {
                await Add_修为(usr_qq, quantity * this_danyao.exp);
                e.reply(`服用成功,修为增加${quantity * this_danyao.exp}`);
                return;
            }
        }

        if (func == "使用") {
            console.log("使用道具");
            let x = await exist_najie_thing(usr_qq, thing_name, "道具");
            if (!x) {
                e.reply(`你没有【${thing_name}】这样的道具`);
                return;
            }

            if (data.daoju_list.find(item => item.name == thing_name).type == "重获灵根") {
                let player = await Read_player(usr_qq);
                let eff1 = player.灵根.eff;
                await Add_najie_thing(usr_qq, thing_name, "道具", -1);
                player.灵根 = await get_random_talent();
                player.修炼效率提升 = player.修炼效率提升 - eff1 + player.灵根.eff;
                await data.setData("player", usr_qq, player);
                e.reply([
                    segment.at(usr_qq),
                    `  服用成功,剩余 ${thing_name}数量: ${x - 1}，新的灵根为 "${player.灵根.type}"：${player.灵根.name}`,
                    "\n可以在【#我的存档】中查看"
                ]);
                return;
            } else if (thing_name == "隐身水") {
                e.reply(`该道具无法在纳戒中使用,在打劫非空闲群友时自动消耗`);
                return;
            }
            else {
                e.reply(`功能开发中,敬请期待`);
                return;
            }

        }

        if (func == "学习") {
            console.log("学习功法");
            let x = await exist_najie_thing(usr_qq, thing_name, "功法");
            if (!x) {
                e.reply(`你没有【${thing_name}】这样的功法`);
                return;
            }

            let player = await Read_player(usr_qq);
            let islearned = player.学习的功法.find(item => item == thing_name);
            if (islearned) {
                e.reply(`你已经学过该功法了`);
                return;
            }
            await Add_najie_thing(usr_qq, thing_name, "功法", -1);
            await Add_player_学习功法(usr_qq, thing_name);
            e.reply(`你学会了${thing_name},可以在【#我的存档】中查看`);
        }
        return;
    }


    //购买商品
    async Buy_comodities(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let thing = e.msg.replace("#", '');
        thing = thing.replace("购买", '');
        let code = thing.split("\*");
        let thing_name = code[0];
        let quantity = 0;
        if (parseInt(code[1]) != parseInt(code[1])) { quantity = 1; }
        else if (parseInt(code[1]) < 1) { e.reply(`输入物品数量小于1,现在默认为1`); quantity = 1; }
        else { quantity = parseInt(code[1]); }
        //e.reply(`thing_name:${thing_name},   quantity:${quantity}`);
        let ifexist = data.commodities_list.find(item => item.name == thing_name);
        if (!ifexist) {
            e.reply(`万宝阁还没有这样的东西:${thing_name}`);
            return;
        }
        let player = await Read_player(usr_qq);
        let lingshi = player.灵石;
        let commodities_price = ifexist.出售价 * 1.5 * quantity;
        if (lingshi < commodities_price) {
            e.reply(`口袋里的灵石不足以支付${thing_name},还需要${commodities_price - lingshi}灵石`);
            return;
        }
        await Add_najie_thing(usr_qq, thing_name, ifexist.class, quantity);
        await Add_灵石(usr_qq, -commodities_price);
        e.reply([`购买成功!  获得${thing_name}*${quantity},花费${commodities_price}灵石,剩余${lingshi - commodities_price}灵石  `,
            '\n可以在【我的纳戒】中查看']);
        return;
    }


    //出售商品
    async Sell_comodities(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let thing = e.msg.replace("#", '');
        thing = thing.replace("出售", '');
        let code = thing.split("\*");
        let thing_name = code[0];
        let quantity = 0;//指令里写的数量
        if (parseInt(code[1]) != parseInt(code[1])) { quantity = 1; }
        else if (parseInt(code[1]) < 1) { e.reply(`输入物品数量小于1,现在默认为1`); quantity = 1; }
        else { quantity = parseInt(code[1]); }
        //e.reply(`thing_name:${thing_name},   quantity:${quantity}`);
        let ifexist = data.commodities_list.find(item => item.name == thing_name);
        if (!ifexist) {
            e.reply(`万宝阁不回收这样的东西:${thing_name}`);
            return;
        }
        //纳戒中的数量
        let thing_quantity = await exist_najie_thing(usr_qq, thing_name, ifexist.class);
        if (!thing_quantity) {//没有
            e.reply(`你没有【${thing_name}】这样的${ifexist.class}`);
            return;
        }
        if (thing_quantity < quantity) {//不够
            e.reply(`你目前只有【${thing_name}】*${x},数量不够`);
            return;
        }
        //数量够,数量减少,灵石增加
        await Add_najie_thing(usr_qq, thing_name, ifexist.class, -quantity);
        let commodities_price = ifexist.出售价 * quantity;
        await Add_灵石(usr_qq, commodities_price);
        e.reply(`出售成功!  获得${commodities_price}灵石,还剩余${thing_name}*${thing_quantity - quantity} `);
        return;
    }


    //闭关
    async Biguan(e) {
        let usr_qq = e.user_id;//用户qq
        //有无存档
        if (!await existplayer(usr_qq)) {
            return;
        }
        if (Lilian_CD[usr_qq]) { e.reply("正在历练中"); return true; }
        //获取时间
        let time = e.msg.replace("#", "");
        time = time.replace("闭关", "");
        time = time.replace("分", "");
        time = time.replace("钟", "");
        if (parseInt(time) == parseInt(time)) {
            time = parseInt(time);
            if (time > 600) {
                time = 600;
                e.reply("一次闭关最多为600分钟");
            } else if (time < 1) {
                time = 10;
                e.reply("闭关时间不能为负数,自动变为默认10分钟");
            }
        } else { time = 10; }//不设置时间默认10分钟
        //查询redis中的人物动作
        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        if (action != null) {
            //人物有动作查询动作结束时间
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }
        let action_time = time * 60 * 1000;//持续时间，单位毫秒
        let arr = {
            "action": "闭关",//动作
            "end_time": new Date().getTime() + action_time,//结束时间
            "is_jiesuan": "0",//是否结算
            "time": action_time//持续时间
        };
        if (e.isGroup) {
            arr.group_id = e.group_id
        }
        await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));//redis设置动作
        e.reply(`现在开始闭关${time}分钟,两耳不闻窗外事了`);

        // await biguaning(e, usr_qq, time);//原本的闭关事件也执行，为了结束的时候给到消息提示
        return true;

    }


    //打工
    async Dagong(e) {
        let usr_qq = e.user_id;//用户qq
        //有无存档
        if (!await existplayer(usr_qq)) {
            return;
        }
        if (Lilian_CD[usr_qq]) { e.reply("正在历练中"); return true; }
        //获取时间
        let time = e.msg.replace("#", "");
        time = time.replace("打工", "");
        time = time.replace("分", "");
        time = time.replace("钟", "");
        if (parseInt(time) == parseInt(time)) {
            time = parseInt(time);
            if (time > 600) {
                time = 600;
                e.reply("一次打工最多为600分钟");
            } else if (time < 1) {
                time = 10;
                e.reply("时间不能为负数,自动变为默认10分钟");
            }
        } else { time = 10; }//不设置时间默认10分钟
        let player = await Read_player(usr_qq);
        if (player.当前血量 < 200) {
            e.reply("你都伤成这样了,先去疗伤吧");
            return;
        }
        //查询redis中的人物动作
        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        if (action != null) {
            //人物有动作查询动作结束时间
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }
        let action_time = time * 60 * 1000;//持续时间，单位毫秒
        let arr = {
            "action": "打工",//动作
            "end_time": new Date().getTime() + action_time,//结束时间
            "is_jiesuan": "0",//是否结算
            "time": action_time//持续时间
        };
        if (e.isGroup) {
            arr.group_id = e.group_id;
        }
        await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));//redis设置动作
        e.reply(`现在开始打工${time}分钟,勤勤恳恳无法外出了`);

        // await dagonging(e, usr_qq, time);//原本的闭关事件也执行，为了结束的时候给到消息提示
        return true;
    }


    //金银坊猜大小
    async Duchang(e) {
        let usr_qq = e.user_id;
        if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        if (Lilian_CD[usr_qq]) { e.reply("正在历练中"); return true; }

        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        if (action != null) {
            //人物有动作查询动作结束时间
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }

        /* dubo cd start */
        let dubo_nowTime = new Date().getTime(); //获取当前时间戳
        let last_dubo_time = await redis.get("xiuxian:player:" + usr_qq + ":last_dubo_time");//获得上次赌博的时间戳,
        last_dubo_time = parseInt(last_dubo_time);
        // console.log("last_dubo_time", last_dubo_time);
        let gamblingTimeout = parseInt(1000 * 60 * this.xiuxianConfigData.CD.gambling);
        if (dubo_nowTime < last_dubo_time + gamblingTimeout) {
            let waittime_m = Math.trunc((last_dubo_time + gamblingTimeout - dubo_nowTime) / 60 / 1000);
            let waittime_s = Math.trunc(((last_dubo_time + gamblingTimeout - dubo_nowTime) % 60000) / 1000);
            e.reply("金银坊正在CD中，" + `剩余cd:  ${waittime_m}分 ${waittime_s}秒`);
            return;
        }

        /* dubo cd end*/
        let player = await Read_player(usr_qq);
        if (player.灵石 < 500) {
            e.reply("门口写着进入金银坊需要随身携带至少500灵石,你羞愧地离开了");
            return;
        }
        if (isdubo[usr_qq] == true) {
            e.reply(`猜大小正在进行哦!`);
            return true;
        }
        e.reply(`发送【押注+数字】或者【梭哈】参与`, true);
        isdubo[usr_qq] = true;
        dubotime[usr_qq] = setTimeout(() => {
            if (isdubo[usr_qq]) {
                e.reply([segment.at(usr_qq), '迟迟没有押注,被后面的人挤到一旁...\n']);
                yazhu[usr_qq] = 0;
                clearTimeout(dubotime[usr_qq]);
                delete isdubo[usr_qq];
                return true;
            }
        }, 30000)//秒数
        return true;
    }

    async jinYinFangLog(e) {
        let qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(qq);
        if (!ifexistplay) {
            return;
        }
        //获取人物信息
        let player_data = data.getData("player", qq);
        let victory = isNotNull(player_data.金银坊胜场) ? player_data.金银坊胜场 : 0;
        let victory_num = isNotNull(player_data.金银坊收入) ? player_data.金银坊收入 : 0;
        let defeated = isNotNull(player_data.金银坊败场) ? player_data.金银坊败场 : 0;
        let defeated_num = isNotNull(player_data.金银坊支出) ? player_data.金银坊支出 : 0;
        let shenglv = 0;
        if (parseInt(victory) + parseInt(defeated) == 0) {
            shenglv = 0;
        } else {
            shenglv = ((victory / (victory + defeated)) * 100).toFixed(2);
        }
        e.reply([segment.at(qq), "\n" +
            "金银坊记录如下：\n" +
            "胜场：" + victory + "\n" +
            "共卷走" + victory_num + "灵石\n" +
            "败场" + defeated + "\n" +
            "送给金银坊" + defeated_num + "灵石\n" +
            "胜率:" + shenglv + "%"]
        );
    }

    async duboCheck(e) {
        let usr_qq = e.user_id;
        let dubo_nowTime = new Date().getTime(); //获取当前时间戳
        //duchangConfig[usr_qq] = getduchangConfig(e);
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay || isdubo[usr_qq] != true) {
            return;
        }
        let es = e.msg.replace('押注', "").trim();
        if (es == '梭哈') {
            let player = await Read_player(usr_qq);
            yazhu[usr_qq] = player.灵石;
            e.reply("押注完成,发送【大】或者【小】参与这一局");
            return true;
        }
        if (parseInt(es) == parseInt(es)) {//判断是不是输了个数字
            let player = await Read_player(usr_qq);
            if (player.灵石 >= parseInt(es)) {
                yazhu[usr_qq] = parseInt(es);
                e.reply("押注完成,发送【大】或者【小】参与这一局");
                return true;
            }
        }
        if (yazhu[usr_qq] > 0) {
            let player = await Read_player(usr_qq);
            //随机数1-6
            let randtime = Math.trunc(Math.random() * 6) + 1;
            let touzi;
            for (var n = 0; n < randtime; n++) {
                touzi = Math.trunc(Math.random() * 6) + 1;
            }
            e.reply(segment.dice(touzi));
            if (es == '大' && touzi > 3 || es == '小' && touzi < 4) {//赢了
                //增加金银坊赌博记录
                if (isNotNull(player.金银坊胜场)) {
                    player.金银坊胜场 = parseInt(player.金银坊胜场) + 1;
                    player.金银坊收入 = parseInt(player.金银坊收入) + parseInt(yazhu[usr_qq]);
                } else {
                    player.金银坊胜场 = 1
                    player.金银坊收入 = parseInt(yazhu[usr_qq]);
                }
                data.setData("player", usr_qq, player);

                Add_灵石(usr_qq, yazhu[usr_qq]);
                console.log("赢了");
                e.reply([segment.at(usr_qq), `骰子最终为 ${touzi} 你猜对了！`, '\n', `现在拥有灵石:${player.灵石 + yazhu[usr_qq]}`]);
                await redis.set("xiuxian:player:" + usr_qq + ":last_dubo_time", dubo_nowTime);//存入缓存
                isdubo[usr_qq] = false;
                yazhu[usr_qq] = 0;
                clearTimeout(dubotime[usr_qq]);
                return true;
            }
            else if (es == '大' && touzi < 4 || es == '小' && touzi > 3) {//输了
                //增加金银坊赌博记录
                if (isNotNull(player.金银坊败场)) {
                    player.金银坊败场 = parseInt(player.金银坊败场) + 1;
                    player.金银坊支出 = parseInt(player.金银坊支出) + parseInt(yazhu[usr_qq]);
                } else {
                    player.金银坊败场 = 1
                    player.金银坊支出 = parseInt(yazhu[usr_qq]);
                }
                data.setData("player", usr_qq, player);

                Add_灵石(usr_qq, -yazhu[usr_qq]);
                console.log("输了");
                let msg = [segment.at(usr_qq), `骰子最终为 ${touzi} 你猜错了！`, '\n', `现在拥有灵石:${player.灵石 - yazhu[usr_qq]}`];
                let now_money = player.灵石 - yazhu[usr_qq];
                await redis.set("xiuxian:player:" + usr_qq + ":last_dubo_time", dubo_nowTime);//存入缓存
                isdubo[usr_qq] = false;
                yazhu[usr_qq] = 0;
                clearTimeout(dubotime[usr_qq]);
                if (now_money <= 0 && this.xiuxianConfigData.ifGamblingLoseGoWork) {
                    //if (is_dagong[usr_qq] != 0 && is_dagong[usr_qq] != 1) { is_dagong[usr_qq] = 0; }//没有初始值就赋值为0
                    //查询redis中的人物动作
                    let time = 10;
                    let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
                    action = JSON.parse(action);
                    if (action != null) {
                        //人物有动作查询动作结束时间
                        let action_end_time = action.end_time;
                        let now_time = new Date().getTime();
                        if (now_time <= action_end_time) {
                            let m = parseInt((action_end_time - now_time) / 1000 / 60);
                            let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                            e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                            return;
                        }
                    }
                    let action_time = time * 60 * 1000;//持续时间，单位毫秒
                    let arr = {
                        "action": "打工",//动作
                        "end_time": new Date().getTime() + action_time,//结束时间
                        "is_jiesuan": "0",//是否结算
                        "time": action_time//持续时间
                    };
                    if (e.isGroup) {
                        arr.group_id = e.group_id;
                    }
                    await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));//redis设置动作

                    msg.push("\n你已经裤衩都输光了,痛定思痛,决定老老实实打工10分钟");
                    // dagonging(e, usr_qq, 10);
                }
                e.reply(msg);
                return true;
            }
        }
        else {
            e.reply("请先押注！");
            return;
        }
    }

    //比武
    async biwu(e) {
        let A = e.user_id;
        let isat = e.message.some((item) => item.type === "at");
        console.log("有无at信息", isat);
        if (!isat) {
            return;
        }
        let atItem = e.message.filter((item) => item.type === "at");
        let B = atItem[0].qq;//后手
        let ifexistplay_A = await existplayer(A);
        if (!ifexistplay_A || e.isPrivate) { return; }
        if (A == B) { e.reply("你是不是精神分裂?"); return; }
        let ifexistplay_B = await existplayer(B);
        if (!ifexistplay_B) { e.reply("对方尚未踏入仙途!"); return; }

        //这里前戏做完,确定要开打了
        let final_msg = [segment.at(A), segment.at(B), "\n"];
        let A_player = await Read_player(A);
        let B_player = await Read_player(B);
        final_msg.push(`${A_player.名号}向${B_player.名号}发起了切磋。`);
        A_player.法球倍率 = A_player.灵根.法球倍率;
        B_player.法球倍率 = B_player.灵根.法球倍率;
        A_player.当前血量 = A_player.血量上限;
        B_player.当前血量 = B_player.血量上限;
        let Data_battle = await Getmsg_battle(A_player, B_player);
        console.log("战斗过程:" + Data_battle)
        let msg = Data_battle.msg;
        //战斗回合过长会导致转发失败报错，所以超过30回合的就不转发了
        if (msg.length > 30) {
            e.reply("战斗过程超过30回合，略");
        } else {
            await ForwardMsg(e, msg);
        }
        //下面的战斗超过100回合会报错
        let A_win = `${A_player.名号}击败了${B_player.名号}`;
        let B_win = `${B_player.名号}击败了${A_player.名号}`;
        if (msg.find(item => item == A_win)) {
            final_msg.push(` 经过一番大战,${A_win},赢得了群友的一阵欢呼`);
        } else if (msg.find(item => item == B_win)) {
            final_msg.push(`经过一番大战,${A_player.名号}被${B_player.名号}击败了,还被群友一阵嘲弄`);
        } else {
            e.reply(`战斗过程出错`);
            return;
        }
        //最后发送消息
        e.reply(final_msg);
        return;
    }


    //打劫
    async Dajie(e) {
        let A = e.user_id;
        let isat = e.message.some((item) => item.type === "at");
        console.log("有无at信息", isat);
        if (!isat) {
            return;
        }
        let atItem = e.message.filter((item) => item.type === "at");
        let B = atItem[0].qq;//被打劫者
        let ifexistplay_A = await existplayer(A);
        if (!ifexistplay_A || e.isPrivate) { return; }
        if (A == B) { e.reply("你是不是精神分裂?"); return; }
        let A_action = await redis.get("xiuxian:player:" + A + ":action");
        A_action = JSON.parse(A_action);
        if (A_action != null) {
            let now_time = new Date().getTime();

            //人物任务的动作是否结束
            let A_action_end_time = A_action.end_time;
            if (now_time <= A_action_end_time) {
                let m = parseInt((A_action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((A_action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + A_action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }
        if (isdubo[A] == true) {
            e.reply(`猜大小正在进行哦!`);
            return true;
        }
        let ifexistplay_B = await existplayer(B);
        if (!ifexistplay_B) { e.reply("对方尚未踏入仙途!"); return; }

        let isBbusy = false;//给B是否忙碌加个标志位，用来判断要不要扣隐身水

        let B_action = await redis.get("xiuxian:player:" + B + ":action");
        B_action = JSON.parse(B_action);
        if (B_action != null) {
            let now_time = new Date().getTime();
            //人物任务的动作是否结束
            let B_action_end_time = B_action.end_time;
            if (now_time <= B_action_end_time) {
                isBbusy = true;
                let ishaveyss = await exist_najie_thing(A, "隐身水", "道具");
                if (!ishaveyss) {//如果A没有隐身水，直接返回不执行
                    let m = parseInt((B_action_end_time - now_time) / 1000 / 60);
                    let s = parseInt(((B_action_end_time - now_time) - m * 60 * 1000) / 1000);
                    e.reply("对方正在" + B_action.action + "中,剩余时间:" + m + "分" + s + "秒");
                    return;
                }
            }
        }


        let now = new Date();
        let nowTime = now.getTime(); //获取当前时间戳
        let last_dajie_time = await redis.get("xiuxian:player:" + A + ":last_dajie_time");//获得上次打劫的时间戳,
        last_dajie_time = parseInt(last_dajie_time);
        console.log("last_dajie_time", last_dajie_time);
        let robTimeout = parseInt(1000 * 60 * this.xiuxianConfigData.CD.rob)
        if (nowTime < last_dajie_time + robTimeout) {
            let waittime_m = Math.trunc((last_dajie_time + robTimeout - nowTime) / 60 / 1000);
            let waittime_s = Math.trunc(((last_dajie_time + robTimeout - nowTime) % 60000) / 1000);
            e.reply("打劫正在CD中，" + `剩余cd:  ${waittime_m}分 ${waittime_s}秒`);
            return;
        }

        let B_player = await Read_player(B);
        if (B_player.当前血量 < 200) { e.reply(`${B_player.名号} 重伤未愈,就不要再打他了`); return; }
        if (B_player.灵石 < 200) { e.reply(`${B_player.名号} 穷得快赶上水脚脚了,就不要再打他了`); return; }
        let final_msg = [segment.at(A), segment.at(B), "\n"];

        //这里前戏做完,确定要开打了
        let A_player = await Read_player(A);

        if (isBbusy) {
            //如果B忙碌,自动扣一瓶隐身水强行打架,奔着人道主义关怀,提前判断了不是重伤
            final_msg.push(`${B_player.名号}正在${B_action.action}，${A_player.名号}使用隐身水悄然接近，但被发现。`);
            await Add_najie_thing(A, "隐身水", "道具", -1);
        }
        else {
            final_msg.push(`${A_player.名号}向${B_player.名号}发起了打劫。`);
        }

        //校验有没有灵根,没有的,随机一个写进存档,之后可以删掉
        if (A_player.灵根 == null || A_player.灵根 == undefined) {
            A_player.灵根 = await get_random_talent();
            A_player.修炼效率提升 += A_player.灵根.eff;
        }
        await data.setData("player", A, A_player);
        if (B_player.灵根 == null || B_player.灵根 == undefined) {
            B_player.灵根 = await get_random_talent();
            B_player.修炼效率提升 += B_player.灵根.eff;
        }
        await data.setData("player", B, B_player);

        A_player.法球倍率 = A_player.灵根.法球倍率;
        B_player.法球倍率 = B_player.灵根.法球倍率;

        let Data_battle = await Getmsg_battle(A_player, B_player);
        console.log("战斗过程:" + Data_battle)
        let msg = Data_battle.msg;
        //战斗回合过长会导致转发失败报错，所以超过30回合的就不转发了
        if (msg.length > 30) {
            e.reply("战斗过程超过30回合，略");
        } else {
            await ForwardMsg(e, msg);
        }
        //下面的战斗超过100回合会报错
        await Add_HP(A, Data_battle.A_xue);
        await Add_HP(B, Data_battle.B_xue);
        let A_win = `${A_player.名号}击败了${B_player.名号}`;
        let B_win = `${B_player.名号}击败了${A_player.名号}`;
        if (msg.find(item => item == A_win)) {
            let lingshi = Math.trunc(B_player.灵石 / 4);
            await Add_灵石(A, lingshi);
            await Add_灵石(B, -lingshi);
            final_msg.push(` 经过一番大战,${A_win},成功劫走${lingshi}灵石`);
        } else if (msg.find(item => item == B_win)) {
            let lingshi = Math.trunc(A_player.灵石 / 4);
            await Add_灵石(A, -lingshi);
            await Add_灵石(B, lingshi);
            final_msg.push(`经过一番大战,${A_player.名号}被${B_player.名号}击败了,真是偷鸡不成蚀把米,被劫走${lingshi}灵石`);
        } else {
            e.reply(`战斗过程出错`);
            return;
        }
        //最后发送消息
        e.reply(final_msg);
        //本次打劫时间存入缓存
        await redis.set("xiuxian:player:" + A + ":last_dajie_time", nowTime);//存入缓存
        return;
    }


    //TOP_xiuwei
    async TOP_xiuwei(e) {
        let usr_qq = e.user_id;
        console.log("命令来自:", usr_qq);
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) { return; }
        let usr_paiming;
        let File = fs.readdirSync(__PATH.player_path);
        File = File.filter(file => file.endsWith(".json"));
        let File_length = File.length;
        let temp = [];
        for (var i = 0; i < File_length; i++) {
            let this_qq = File[i].replace(".json", '');
            this_qq = parseInt(this_qq);
            let player = await Read_player(this_qq);
            let sum_exp = await Get_xiuwei(this_qq);
            temp[i] = {
                总修为: sum_exp,
                境界: player.境界,
                名号: player.名号,
                qq: this_qq
            }
        }
        //排序
        temp.sort(sortBy("总修为"));
        usr_paiming = temp.findIndex(temp => temp.qq === usr_qq) + 1;
        let msg = [
            "****修为排行榜****"
        ];
        if (File_length > 10) { File_length = 10; }//最多显示前十
        for (var i = 0; i < File_length; i++) {
            msg.push("第" + `${i + 1}` + "名:\n" + `名号:${temp[i].名号}` + '\n' + `境界:${temp[i].境界}` + '\n' + `总修为${temp[i].总修为}`);
            console.log(temp[i]);
        }
        e.reply([segment.at(usr_qq), `你在修为榜中排名第${usr_paiming},修仙之路永无止境,请继续加油!`]);
        await ForwardMsg(e, msg);
        return;
    }


    //TOP_lingshi
    async TOP_lingshi(e) {
        let usr_qq = e.user_id;
        console.log("命令来自:", usr_qq);
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) { return; }
        let usr_paiming;
        let File = fs.readdirSync(__PATH.player_path);
        File = File.filter(file => file.endsWith(".json"));
        let File_length = File.length;
        let temp = [];
        for (var i = 0; i < File_length; i++) {
            let this_qq = File[i].replace(".json", '');
            this_qq = parseInt(this_qq);
            let player = await Read_player(this_qq);
            let najie = await Read_najie(this_qq);
            let lingshi = player.灵石 + najie.灵石;
            temp[i] = {
                ls1: najie.灵石,
                ls2: player.灵石,
                灵石: lingshi,
                名号: player.名号,
                qq: this_qq
            }
        }
        //排序
        temp.sort(sortBy("灵石"));
        usr_paiming = temp.findIndex(temp => temp.qq === usr_qq) + 1;
        let msg = [
            "****灵石排行榜****"
        ];
        if (File_length > 10) { File_length = 10; }//最多显示前十
        for (var i = 0; i < File_length; i++) {
            msg.push("第" + `${i + 1}` + "名:\n" + `名号:${temp[i].名号}` + '\n' + `总灵石数:${temp[i].灵石}` + '\n' + `其中纳戒储存灵石数:${temp[i].ls1}` +
                `  未储存灵石数${temp[i].ls2}`);
            console.log(temp[i]);
        }
        e.reply([segment.at(usr_qq), `你在灵石榜中排名第${usr_paiming},财富源于积少成多,请继续加油!`]);
        await sleep(500);
        await ForwardMsg(e, msg);
        return;

    }



    //外出历练
    async Lilian(e) {
        let usr_qq = e.user_id;
        //有无存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) { return; }
        if (Lilian_CD[usr_qq]) { e.reply("正在历练中"); return true; }
        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        if (action != null) {
            //人物有动作查询动作结束时间
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }
        let player = await Read_player(usr_qq);
        if (player.灵石 < 500) {
            e.reply("没有灵石寸步难行,攒到500灵石才够一次外出历练");
            return true;
        }
        if (player.当前血量 < 200) {
            e.reply("你都伤成这样了,就不要出去浪了");
            return;
        }
        Add_灵石(usr_qq, -500);
        e.reply("开始历练了,十分钟后回来!");
        //一个CD
        Lilian_CD[usr_qq] = true;
        Lilian_CD[usr_qq] = setTimeout(() => {
            if (Lilian_CD[usr_qq]) {
                delete Lilian_CD[usr_qq];
                lilian(e);
            }
        }, 60000 * 10);//这里是冷却时间，单位毫秒，60000 -> 一分钟.
        return;
    }


    //孝敬大佬A扣钱，B加钱，手续费1%（奸商啊）
    async Give_lingshi(e) {
        let isat = e.message.some((item) => item.type === "at");
        console.log("有无at信息", isat);
        if (!isat) { return; }//没有at信息直接返回,不执行
        let atItem = e.message.filter((item) => item.type === "at");//获取at信息
        let B_qq = atItem[0].qq;
        let A_qq = e.user_id;
        //双方是否有存档
        let ifexistplay = await existplayer(A_qq);
        if (!ifexistplay) { return; }
        ifexistplay = await existplayer(B_qq);
        if (!ifexistplay) { e.reply(`此人尚未踏入仙途`); return; }

        if (isdubo[A_qq] == true) {
            e.reply(`猜大小正在进行哦!`);
            return true;
        }
        console.log("开始");
        //获取发送灵石数量
        let lingshi = e.msg.replace("#", "");
        lingshi = lingshi.replace("孝敬前辈", "");
        lingshi = lingshi.replace("资助后辈", "");
        lingshi = lingshi.replace("赠送灵石", "");
        //校验输入灵石数
        if (parseInt(lingshi) == parseInt(lingshi) && parseInt(lingshi) >= 1000) {
            lingshi = parseInt(lingshi);
        }
        else {
            e.reply(`这么点灵石你也好拿得出手吗?起码要1000灵石,已为您修改`);
            lingshi = 1000;
        }//没有输入正确数字或＜1000;
        //检验A有没有那么多灵石
        let A_player = await data.getData("player", A_qq);
        let B_player = await data.getData("player", B_qq);
        if (A_player.灵石 < lingshi) {
            e.reply([segment.at(A_qq), `你身上似乎没有${lingshi}灵石`]);
            return;
        }

        let now = new Date();
        let nowTime = now.getTime(); //获取当前时间戳
        let lastgetbung_time = await redis.get("xiuxian:player:" + B_qq + ":last_getbung_time");//获得上次B得到贿金的时间戳,
        lastgetbung_time = parseInt(lastgetbung_time);
        let transferTimeout = parseInt(this.xiuxianConfigData.CD.transfer * 1000 * 60 * 1)
        //console.log("lastgetbung_time", lastgetbung_time);
        if (nowTime < lastgetbung_time + transferTimeout) {
            let waittime_m = Math.trunc((lastgetbung_time + transferTimeout - nowTime) / 60 / 1000);
            let waittime_s = Math.trunc(((lastgetbung_time + transferTimeout - nowTime) % 60000) / 1000);
            e.reply(`每${transferTimeout / 1000 / 60}分钟只能被赠送灵石一次，对方正在CD中，` + `剩余cd: ${waittime_m}分${waittime_s}秒`);
            return;
        }

        //交易
        await Add_灵石(A_qq, -lingshi);
        let lastlingshi = Math.trunc(lingshi * 0.99);//收手续费
        await Add_灵石(B_qq, lastlingshi);
        e.reply([segment.at(A_qq), segment.at(B_qq), `交易成功,${B_player.名号} 获得了由 ${A_player.名号}赠送的${lingshi}灵石,扣除手续费后最终获得${lastlingshi}灵石`])
        //记录本次获得赠送灵石的时间戳
        await redis.set("xiuxian:player:" + B_qq + ":last_getbung_time", nowTime);
        return;
    }

    //发福利
    async Fuli(e) {
        if (!e.isMaster) {
            e.reply("只有主人可以执行操作");
            return;
        }
        console.log("开始");
        //获取发送灵石数量
        let lingshi = e.msg.replace("#", "");
        lingshi = lingshi.replace("发", "");
        lingshi = lingshi.replace("福利", "");
        lingshi = lingshi.replace("补偿", "");
        //校验输入灵石数
        if (parseInt(lingshi) == parseInt(lingshi) && parseInt(lingshi) > 0) {
            lingshi = parseInt(lingshi);
        }
        else {
            lingshi = 100;//没有输入正确数字或不是正数
        }

        let isat = e.message.some((item) => item.type === "at");
        console.log("有无at信息", isat);
        if (isat) {
            let atItem = e.message.filter((item) => item.type === "at");
            let this_qq = atItem[0].qq;
            //有无存档
            let ifexistplay = await existplayer(this_qq);
            if (!ifexistplay) {
                e.reply(`此人尚未踏入仙途`);
                return;
            }
            await Add_灵石(this_qq, lingshi);
            e.reply(`福利发放成功, ${this_qq} 增加${lingshi}灵石`);
            let new_log = `主人偷偷给 ${this_qq} 发了:${lingshi}灵石`;
            await set_log(new_log);
            return;
        }
        else {
            let new_log = `全服发送福利:${lingshi}灵石`;
            await set_log(new_log);
            let File = fs.readdirSync(__PATH.player_path);
            File = File.filter(file => file.endsWith(".json"));
            console.log("file:", File);
            let File_length = File.length;
            for (var i = 0; i < File_length; i++) {
                let this_qq = File[i].replace(".json", '');
                await Add_灵石(this_qq, lingshi);
            }
            //发送消息
            e.reply(`福利发放成功,目前共有${File_length}个玩家,每人增加${lingshi}灵石`);
            return;
        }
    }



    //最近公告
    async last_Log(e) {
        let log_msg = await get_log();
        e.reply(log_msg);
        return;
    }

    //来张卡片
    async getOneCard(e){
        let template_path=await common.getTemplatePath();
        let cards=["A","2","3","4","5","6","7","8","9","10","J","Q","K"];//扑克数字
        let backgroundList=["01.jpg","02.jpg","10.jpg"];//背景图片
        let card_border=["orange","white","rebeccapurple"];//边框颜色,最好是跟图片对应
        let flower_color=["红桃.png","方片.png","黑桃.png","梅花.png"];
        let font_color=["red","red","black","black"]
        let random=parseInt(Math.random()*3);
        let random_color=parseInt(Math.random()*4);
        let arr = {
            size: cards[parseInt(Math.random()*12)],
            flower_color: flower_color[random_color],
            font_color:font_color[random_color],
            img_path: template_path,
            background_img: backgroundList[random],
            background_color:card_border[random]
        }
        await common.generateHtml(template_path+"template/poke/poke.html",template_path+"html/poke.html",arr);
        let param = {
            clip: {
                x:0,
                y:0,
                width:310,
                height:470
            }
        };
        let img = await common.generateImgByHtml(template_path+"html/poke.html",template_path+"img/poke.jpg",param);
        e.reply([segment.image(img)]);
        return;
    }

    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓按理来讲这个括号在我的vscode是黄色的
}


//写入log信息
async function set_log(data) {
    //获取时间
    let now = new Date();
    let nowTime = now.getTime(); //获取当前日期的时间戳
    let logfile = [];
    let nowlog = {
        time: timestampToTime(nowTime),
        content: data,
    }
    let dir = path.join(`${__PATH.log_path}/xiuxian_log.json`);
    logfile = fs.readFileSync(dir, 'utf8');
    logfile = JSON.parse(logfile);
    logfile.unshift(nowlog);
    let logARR = JSON.stringify(logfile, "", "\t");
    fs.writeFileSync(dir, logARR, 'utf8');
    return;
}

//读取log信息
async function get_log() {
    let dir = path.join(`${__PATH.log_path}/xiuxian_log.json`);
    let logfile = fs.readFileSync(dir, 'utf8');
    logfile = JSON.parse(logfile);
    let log_length = 10;
    if (logfile.length < 10) {
        log_length = logfile.length;
    }
    let msg = [];

    if (!isNotNull(logfile[0])) {
        msg.push(`暂时没有记录`);
    }
    else {
        msg.push(`最近${log_length}条记录:`);
        for (var i = 0; i < log_length; i++) {
            msg.push("\n" + `[${logfile[i].time}]${logfile[i].content}`);
        }
    }

    return msg;
}

//历练
async function lilian(e) {
    let usr_qq = e.user_id;
    let player = await Read_player(usr_qq);
    if (player.灵根 == null || player.灵根 == undefined) {
        player.灵根 = await get_random_talent();
        player.修炼效率提升 += player.灵根.eff;
    }
    await data.setData("player", usr_qq, player);
    let A_player = {
        名号: player.名号,
        攻击: player.攻击,
        防御: player.防御,
        当前血量: player.当前血量,
        暴击率: player.暴击率,
        法球倍率: player.灵根.法球倍率
    }
    let monster_length = data.monster_list.length;
    let monster_index = Math.trunc(Math.random() * monster_length);
    let monster = data.monster_list[monster_index];
    let B_player = {
        名号: monster.名号,
        攻击: parseInt(player.攻击 * monster.攻击),
        防御: parseInt(player.防御 * monster.防御),
        当前血量: parseInt(player.血量上限 * monster.当前血量),
        暴击率: monster.暴击率,
        法球倍率: 0
    }
    let Data_battle = await Getmsg_battle(A_player, B_player);
    let msg = Data_battle.msg;
    let last_msg;
    let A_win = `${A_player.名号}击败了${B_player.名号}`;
    let B_win = `${B_player.名号}击败了${A_player.名号}`;
    let xiuwei = 0;
    let Player_level_id = data.Level_list.find(item => item.level == player.境界).level_id;
    if (msg.find(item => item == A_win)) {
        xiuwei = parseInt((2000 + Player_level_id * Player_level_id));//增加的修为
        last_msg = `历练回来了,在历练的过程中,你遇到了${B_player.名号},经过一番战斗,击败对手,获得修为${xiuwei}`;
    }
    else if (msg.find(item => item == B_win)) {
        xiuwei = 500;
        last_msg = `历练回来了,在历练的过程中,你遇到了${B_player.名号},经过一番战斗,败下阵来,还好跑得快,获得修为${xiuwei}`;

    }
    else {
        e.reply(`战斗过程出错`);
        return;
    }
    await ForwardMsg(e, msg);
    await Add_HP(usr_qq, Data_battle.A_xue);
    await Add_修为(usr_qq, xiuwei);
    e.reply([segment.at(usr_qq), last_msg]);
}



//以下方法调用时不加await很可能不同步导致出错

//检查存档是否存在，存在返回true;
async function existplayer(usr_qq) {
    let exist_player;
    exist_player = fs.existsSync(`${__PATH.player_path}/${usr_qq}.json`);
    if (exist_player) {
        return true;
    }
    return false;
}


//读取存档信息，返回成一个JavaScript对象
async function Read_player(usr_qq) {
    let dir = path.join(`${__PATH.player_path}/${usr_qq}.json`);
    let player = fs.readFileSync(dir, 'utf8', (err, data) => {
        if (err) {
            console.log(err)
            return "error";
        }
        return data;
    })
    //将字符串数据转变成数组格式
    player = JSON.parse(player);
    return player;
}


//写入存档信息,第二个参数是一个JavaScript对象
async function Write_player(usr_qq, player) {
    let dir = path.join(__PATH.player_path, `${usr_qq}.json`);
    let new_ARR = JSON.stringify(player, "", "\t");
    fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
        console.log('写入成功', err)
    })
    return;
}


//读取装备信息，返回成一个JavaScript对象
async function Read_equipment(usr_qq) {
    let dir = path.join(`${__PATH.equipment_path}/${usr_qq}.json`);
    let equipment = fs.readFileSync(dir, 'utf8', (err, data) => {
        if (err) {
            console.log(err)
            return "error";
        }
        return data;
    })
    //将字符串数据转变成数组格式
    equipment = JSON.parse(equipment);
    return equipment;
}


//写入装备信息,第二个参数是一个JavaScript对象
async function Write_equipment(usr_qq, equipment) {
    //每次写入都要更新新的攻防生
    let equ_atk = equipment.武器.atk + equipment.护具.atk + equipment.法宝.atk;
    let equ_def = equipment.武器.def + equipment.护具.def + equipment.法宝.def;
    let equ_HP = equipment.武器.HP + equipment.护具.HP + equipment.法宝.HP;
    let equ_bao = equipment.武器.bao + equipment.护具.bao + equipment.法宝.bao;
    let player = await Read_player(usr_qq);
    player["攻击"] = equ_atk + player.基础攻击;
    player["防御"] = equ_def + player.基础防御;
    player["血量上限"] = equ_HP + player.基础血量;
    player["暴击率"] = equ_bao + player.基础暴击;
    await Write_player(usr_qq, player);
    await Add_HP(usr_qq, 0);
    let dir = path.join(__PATH.equipment_path, `${usr_qq}.json`);
    let new_ARR = JSON.stringify(equipment, "", "\t");
    fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
        console.log('写入成功', err)
    })
    return;
}


//读取纳戒信息，返回成一个JavaScript对象
async function Read_najie(usr_qq) {
    let dir = path.join(`${__PATH.najie_path}/${usr_qq}.json`);
    let najie = fs.readFileSync(dir, 'utf8', (err, data) => {
        if (err) {
            console.log(err)
            return "error";
        }
        return data;
    })
    //将字符串数据转变成数组格式
    najie = JSON.parse(najie);
    return najie;
}


//写入纳戒信息,第二个参数是一个JavaScript对象
async function Write_najie(usr_qq, najie) {
    let dir = path.join(__PATH.najie_path, `${usr_qq}.json`);
    let new_ARR = JSON.stringify(najie, "", "\t");
    fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
        console.log('写入成功', err)
    })
    return;
}


//修为数量和灵石数量正增加,负减少
//使用时记得加await
async function Add_灵石(usr_qq, 灵石数量 = 0) {
    let player = await Read_player(usr_qq);
    player.灵石 += 灵石数量;
    await Write_player(usr_qq, player);
    return;
}
async function Add_修为(usr_qq, 修为数量 = 0) {
    let player = await Read_player(usr_qq);
    player.修为 += 修为数量;
    await Write_player(usr_qq, player);
    return;
}
async function Add_HP(usr_qq, blood = 0) {
    let player = await Read_player(usr_qq);
    player.当前血量 += blood;
    if (player.当前血量 > player.血量上限) {
        player.当前血量 = player.血量上限;
    }
    await Write_player(usr_qq, player);
    return;
}
async function Add_najie_灵石(usr_qq, lingshi) {
    let najie = await Read_najie(usr_qq);
    najie.灵石 = najie.灵石 + lingshi;
    await Write_najie(usr_qq, najie);
    return;
}

async function Add_player_学习功法(usr_qq, gongfa_name) {
    let gongfa_效率 = data.gongfa_list.find(item => item.name === gongfa_name).修炼加成;
    let player = await Read_player(usr_qq);
    if (parseInt(player.修炼效率提升) != parseInt(player.修炼效率提升)) { player.修炼效率提升 = 0; }
    player.修炼效率提升 += gongfa_效率;
    player.学习的功法.push(gongfa_name);
    await Write_player(usr_qq, player);
    return;
}

//检查纳戒内物品是否存在
//要用await
async function exist_najie_thing(usr_qq, thing_name, thing_class) {
    let najie = await Read_najie(usr_qq);
    let ifexist;
    if (thing_class == "装备") {
        ifexist = najie.装备.find(item => item.name == thing_name);
    }
    if (thing_class == "丹药") {
        ifexist = najie.丹药.find(item => item.name == thing_name);
    }
    if (thing_class == "道具") {
        ifexist = najie.道具.find(item => item.name == thing_name);
    }
    if (thing_class == "功法") {
        ifexist = najie.功法.find(item => item.name == thing_name);
    }
    //console.log(ifexist.数量);
    if (ifexist) {
        return ifexist.数量;
    }
    return false;
}


/**
 * 增加减少纳戒内物品
 * @param usr_qq 操作存档的qq号
 * @param thing_name  物品名称 
 * @param thing_class  物品类别
 * @param n  操作的数量,取+增加,取 -减少
 * @returns 无
 */
async function Add_najie_thing(usr_qq, thing_name, thing_class, n) {
    if (n === 0) { n = 1 };//这个都是自己调用应该不会范这个错误
    let najie = await Read_najie(usr_qq);
    let exist = await exist_najie_thing(usr_qq, thing_name, thing_class);
    //这部分写得很冗余,但能跑
    if (thing_class == "装备") {
        if (n > 0 && !exist) {//无中生有
            najie.装备.push(data.equipment_list.find(item => item.name == thing_name));
            najie.装备.find(item => item.name == thing_name).数量 = n;
            await Write_najie(usr_qq, najie);
            return;
        }
        najie.装备.find(item => item.name == thing_name).数量 += n;
        if (najie.装备.find(item => item.name == thing_name).数量 < 1) {
            //假如用完了,需要删掉数组中的元素,用.filter()把!=该元素的过滤出来
            najie.装备 = najie.装备.filter(item => item.name != thing_name);
        }
        await Write_najie(usr_qq, najie);
        return;
    }
    if (thing_class == "丹药") {
        if (n > 0 && !exist) {//无中生有
            najie.丹药.push(data.danyao_list.find(item => item.name == thing_name));
            najie.丹药.find(item => item.name == thing_name).数量 = n;
            await Write_najie(usr_qq, najie);
            return;
        }
        najie.丹药.find(item => item.name == thing_name).数量 += n;
        if (najie.丹药.find(item => item.name == thing_name).数量 < 1) {
            //假如用完了,需要删掉数组中的元素,用.filter()把!=该元素的过滤出来
            najie.丹药 = najie.丹药.filter(item => item.name != thing_name);
        }
        await Write_najie(usr_qq, najie);
        return;
    }
    if (thing_class == "道具") {
        if (n > 0 && !exist) {//无中生有
            najie.道具.push(data.daoju_list.find(item => item.name == thing_name));
            najie.道具.find(item => item.name == thing_name).数量 = n;
            await Write_najie(usr_qq, najie);
            return;
        }
        najie.道具.find(item => item.name == thing_name).数量 += n;
        if (najie.道具.find(item => item.name == thing_name).数量 < 1) {
            //假如用完了,需要删掉数组中的元素,用.filter()把!=该元素的过滤出来
            najie.道具 = najie.道具.filter(item => item.name != thing_name);
        }
        await Write_najie(usr_qq, najie);
        return;
    }
    if (thing_class == "功法") {
        if (n > 0 && !exist) {//无中生有
            najie.功法.push(data.gongfa_list.find(item => item.name == thing_name));
            najie.功法.find(item => item.name == thing_name).数量 = n;
            await Write_najie(usr_qq, najie);
            return;
        }
        najie.功法.find(item => item.name == thing_name).数量 += n;
        if (najie.功法.find(item => item.name == thing_name).数量 < 1) {
            //假如用完了,需要删掉数组中的元素,用.filter()把!=该元素的过滤出来
            najie.功法 = najie.功法.filter(item => item.name != thing_name);
        }
        await Write_najie(usr_qq, najie);
        return;
    }
    return;
}


//替换装备
async function instead_equipment(usr_qq, thing_name) {
    await Add_najie_thing(usr_qq, thing_name, "装备", -1);
    let thing_type = data.equipment_list.find(item => item.name == thing_name).type;
    let equipment = await Read_equipment(usr_qq);
    if (thing_type == "武器") {
        await Add_najie_thing(usr_qq, equipment.武器.name, "装备", 1);
        equipment.武器 = data.equipment_list.find(item => item.name == thing_name);
        await Write_equipment(usr_qq, equipment);
        return;
    }
    if (thing_type == "护具") {
        await Add_najie_thing(usr_qq, equipment.护具.name, "装备", 1);
        equipment.护具 = data.equipment_list.find(item => item.name == thing_name);
        await Write_equipment(usr_qq, equipment);
        return;
    }
    if (thing_type == "法宝") {
        await Add_najie_thing(usr_qq, equipment.法宝.name, "装备", 1);
        equipment.法宝 = data.equipment_list.find(item => item.name == thing_name);
        await Write_equipment(usr_qq, equipment);
        return;
    }
    return;
}

//赌博事件参数设置
var yazhu = [];
let isdubo = [];
let dubotime = [];


//获取A打B的消息，A、B为两个人QQ号，返回一个字符串数组
//A打先手
/*
player ={
    攻击:123,
    防御:123,
    当前血量:123,
    暴击率:0.123,
    名号:"ABC",
    qq:123,
    法球倍率: 0.02

}
*/
async function Getmsg_battle(A_player, B_player) {
    let now_A_HP = A_player.当前血量;//保留初始血量方便计算最后扣多少血,避免反复读写文件
    let now_B_HP = B_player.当前血量;
    let A_xue = 0;//最后要扣多少血
    let B_xue = 0;


    let cnt = 0;//回合数
    let msg = [];
    while (A_player.当前血量 > 0 && B_player.当前血量 > 0) {
        if (cnt % 2 == 0) {
            let baoji = baojishanghai(A_player.暴击率);
            let 伤害 = Harm(A_player.攻击, B_player.防御);
            let 法球伤害 = Math.trunc(A_player.攻击 * A_player.法球倍率);
            伤害 = Math.trunc(baoji * 伤害 + 法球伤害);
            B_player.当前血量 -= 伤害;
            if (B_player.当前血量 < 0) { B_player.当前血量 = 0 }
            msg.push(`第${Math.trunc(cnt / 2) + 1}回合：
${A_player.名号}攻击了${B_player.名号}，${ifbaoji(baoji)}造成伤害${伤害}，造成额外伤害${法球伤害}，${B_player.名号}剩余血量${B_player.当前血量}`);
        }
        if (cnt % 2 == 1) {
            let baoji = baojishanghai(B_player.暴击率);
            let 伤害 = Harm(B_player.攻击, A_player.防御);
            let 法球伤害 = Math.trunc(B_player.攻击 * B_player.法球倍率);
            伤害 = Math.trunc(baoji * 伤害 + 法球伤害);
            A_player.当前血量 -= 伤害;
            if (A_player.当前血量 < 0) { A_player.当前血量 = 0 }
            msg.push(`第${Math.trunc(cnt / 2) + 1}回合：
${B_player.名号}攻击了${A_player.名号}，${ifbaoji(baoji)}造成伤害${伤害}，造成额外伤害${法球伤害}，${A_player.名号}剩余血量${A_player.当前血量}`);
        }
        cnt++;
    }
    if (A_player.当前血量 <= 0) {
        msg.push(`${B_player.名号}击败了${A_player.名号}`);
        B_xue = B_player.当前血量 - now_B_HP;
        A_xue = -now_A_HP;
    }
    if (B_player.当前血量 <= 0) {
        msg.push(`${A_player.名号}击败了${B_player.名号}`);
        B_xue = -now_B_HP;
        A_xue = A_player.当前血量 - now_A_HP;
    }
    let Data_nattle = {
        "msg": msg,
        "A_xue": A_xue,
        "B_xue": B_xue
    }
    return Data_nattle;
}

//通过输入暴击率,返回暴击伤害,不暴击返回1
function baojishanghai(baojilv) {
    if (baojilv > 1) { baojilv = 1; }//暴击率最高为100%,即1
    let rand = Math.random();
    let bl = 1;
    if (rand < baojilv) {
        bl = baojilv + 2;//这个是暴击伤害倍率//满暴击时暴伤为300%
    }
    return bl;
}

//通过暴击伤害返回输出用的文本
function ifbaoji(baoji) {
    if (baoji == 1) { return ""; }
    else { return '触发暴击，'; }
}


//攻击攻击防御计算伤害
function Harm(atk, def) {
    let x;
    let s = atk / def;
    let rand = Math.trunc(Math.random() * 11) / 100 + 0.95;//保留±5%的伤害波动
    if (s < 1) {
        x = 0.1;
    }
    else if (s > 2.5) {
        x = 1;
    }
    else {
        x = 0.6 * s - 0.5;
    }
    x = Math.trunc(x * atk * rand);
    return x;
}

//色图
async function setu(e) {
    let url;
    e.reply(`玩命加载图片中,请稍后...   `+"\n(一分钟后还没有出图片,大概率被夹了,这个功能谨慎使用,机器人容易寄)")
    url = "https://api.lolicon.app/setu/v2?proxy=i.pixiv.re&r18=0";//setu接口地址
    let msg = [];
    let res;
    try {
        let response = await fetch(url);
        res = await response.json();
    } catch (error) {
        console.log('Request Failed', error);
    }
    //console.log(res);
    if (res !== '{}') { console.log('res不为空'); } else { console.log('res为空'); }
    let link = res.data[0].urls.original;//获取图链
    link = link.replace('pixiv.cat', 'pixiv.re');//链接改为国内可访问的域名
    let pid = res.data[0].pid;//获取图片ID
    let uid = res.data[0].uid;//获取画师ID
    let title = res.data[0].title;//获取图片名称
    let author = res.data[0].author;//获取画师名称
    let px = res.data[0].width + '*' + res.data[0].height;//获取图片宽高
    msg.push("User: " + author +
        "\nUid: " + uid +
        "\nTitle: " + title +
        "\nPid: " + pid +
        "\nPx: " + px +
        "\nLink: " + link);
    await sleep(1000);

    //最后回复消息
    e.reply(segment.image(link));
    await ForwardMsg(e, msg);
    return true; //返回true 阻挡消息不再往下
}



//发送转发消息
//输入data一个数组,元素是字符串,每一个元素都是一条消息.
export async function ForwardMsg(e, data) {
    //console.log(data);
    let msgList = [];
    for (let i of data) {
        msgList.push({
            message: i,
            nickname: Bot.nickname,
            user_id: Bot.uin,
        });
    }
    if (msgList.length == 1) {
        await e.reply(msgList[0].message);
    }
    else {
        //console.log(msgList);
        await e.reply(await Bot.makeForwardMsg(msgList));
    }
    return;
}


//对象数组排序
function sortBy(field) {//从大到小,b和a反一下就是从小到大
    return function (b, a) {
        return a[field] - b[field];
    }
}


//获取总修为
async function Get_xiuwei(usr_qq) {
    let player = await Read_player(usr_qq);
    let sum_exp = 0;
    let level_id = data.Level_list.find(temp => temp.level == player.境界).level_id;
    console.log('level_id=', level_id);
    if (level_id < 39) {
        for (var i = 1; i < level_id; i++) {
            sum_exp = sum_exp + data.Level_list.find(temp => temp.level_id == i).exp;
        }
    }
    else { sum_exp = -999999999; }//说明玩家境界有错误

    sum_exp += player.修为;
    return sum_exp;
}


//加起来得是1
const 伪灵根概率 = 0.6;
const 真灵根概率 = 0.35;
const 天灵根概率 = 0.03;
const 变异灵根概率 = 1 - 伪灵根概率 - 真灵根概率 - 天灵根概率;

//获取随机灵根
export async function get_random_talent() {
    let talent;
    if (get_random_res(伪灵根概率)) {
        talent = data.talent_list.filter(item => item.type == "伪灵根");
    }
    else if (get_random_res(真灵根概率 / (1 - 伪灵根概率))) {
        talent = data.talent_list.filter(item => item.type == "真灵根");
    }
    else if (get_random_res(天灵根概率 / (1 - 真灵根概率 - 伪灵根概率))) {
        talent = data.talent_list.filter(item => item.type == "天灵根");
    }
    else {
        talent = data.talent_list.filter(item => item.type == "变异灵根");
    }
    let newtalent = get_random_fromARR(talent)
    console.log("获得灵根", newtalent);
    return newtalent;
}


/**
 * 输入概率随机返回布尔类型数据
 * @param P 概率
 * @returns 随机返回 false or true
 */
function get_random_res(P) {
    if (P > 1) { P = 1; }
    if (P < 0) { P = 0; }
    //console.log(P);
    let rand = Math.random();
    //console.log(rand);
    if (rand < P) {
        return true;
    }
    return false;
}
/**
 * 输入数组随机返回其中一个
 * @param ARR 输入的数组
 * @returns 随机返回一个元素
 */
export function get_random_fromARR(ARR) {
    //let L = ARR.length;
    let randindex = Math.trunc(Math.random() * ARR.length);
    console.log("数组:", randindex)

    return ARR[randindex];
}

//sleep
async function sleep(time) {
    return new Promise(resolve => {
        setTimeout(resolve, time);
    })
}

// 时间转换
export function timestampToTime(timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
}


//根据时间戳获取年月日时分秒
export async function shijianc(time) {
    let dateobj = {}
    var date = new Date(time)
    dateobj.Y = date.getFullYear()
    dateobj.M = date.getMonth() + 1
    dateobj.D = date.getDate()
    dateobj.h = date.getHours()
    dateobj.m = date.getMinutes()
    dateobj.s = date.getSeconds()
    //let nowTime = `${dateobj.Y}年${dateobj.M}月${dateobj.D}日${dateobj.h}时${dateobj.m}分${dateobj.s}秒`
    return dateobj

}
//获取上次签到时间
async function getLastsign(usr_qq) {
    //查询redis中的人物动作
    let time = await redis.get("xiuxian:player:" + usr_qq + ":lastsign_time");
    console.log(time);
    if (time != null) {
        let data = await shijianc(parseInt(time))
        return data;
    }
    return false;
}


//获取当前人物状态
async function getPlayerAction(usr_qq) {
    //查询redis中的人物动作
    let arr = {};
    let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
    action = JSON.parse(action);
    if (action != null) {
        //人物有动作查询动作结束时间
        let action_end_time = action.end_time;
        let now_time = new Date().getTime();
        if (now_time <= action_end_time) {
            let m = parseInt((action_end_time - now_time) / 1000 / 60);
            let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
            arr.action = action.action;//当期那动作
            arr.time = m + "分" + s + "秒";//剩余时间
            return arr;
        }
    }
    arr.action = "空闲";
    return arr;
}

/**
 * 判断对象是否不为undefined且不为null
 * @param obj 对象
 * @returns obj==null/undefined,return false,other return true
 */
function isNotNull(obj) {
    if (obj == undefined || obj == null)
        return false;
    return true;
}

function isNotBlank(value) {
    if (value ?? '' !== '') {
        return true;
    } else {
        return false;
    }
}

